package org.fatmansoft.teach.controllers;

import org.apache.poi.xssf.usermodel.*;
import org.fatmansoft.teach.models.*;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import org.fatmansoft.teach.repository.HonourRepository;
import org.fatmansoft.teach.repository.PersonRepository;
import org.fatmansoft.teach.service.HonourService;
import org.fatmansoft.teach.util.CommonMethod;
import org.fatmansoft.teach.util.DateTimeTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.validation.Valid;
import java.util.*;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/honour")
public class HonourController {
    @Autowired
    private HonourRepository honourRepository;
    @Autowired
    private PersonRepository personRepository;
    @Autowired
    private HonourService honourService;

    @PostMapping("/getHonourPageData")
    @PreAuthorize(" hasRole('ADMIN')")
    public DataResponse getHonourPageData(@Valid @RequestBody DataRequest dataRequest) {

        String numName = dataRequest.getString("numName");
        Integer cPage = dataRequest.getCurrentPage();
        int dataTotal = 0;
        int size = 40;
        Page<Honour> page = null;
        List dataList = new ArrayList();
        Pageable pageable = PageRequest.of(cPage, size);
        page = honourRepository.findHonourPageByNumName(numName, pageable);
        Map m;
        Honour h;
        if(page != null){  //如果查询出的数据不是空
            dataTotal = (int) page.getTotalElements();  //数据总数
            List list = page.getContent();  //转换成list格式
            if(list != null && list.size() > 0){  //表示list中有数据
                for (int i = 0; i < list.size(); i++) {  //遍历list中的每一条数据
                    h = (Honour) list.get(i);  //类型转换
                    m = honourService.getMapFromHonour(h); //数据解析
//                    System.out.println(m.toString());
                    dataList.add(m);
                }
            }
        }
        HashMap data = new HashMap();
        data.put("dataTotal", dataTotal);
        data.put("pageSize", size);
        data.put("dataList", dataList);
        return CommonMethod.getReturnData(data);
    }

    @PostMapping("/honourDelete")
    @PreAuthorize(" hasRole('ADMIN')")
    public DataResponse honourDelete(@Valid @RequestBody DataRequest dataRequest) {
        Integer honourId = dataRequest.getInteger("honourId");  //获取要删除的荣誉id
        honourRepository.deleteById(honourId); //通过id删除
        return  CommonMethod.getReturnMessageOK();
    }


    @PostMapping("/honourEditSave")
    @PreAuthorize(" hasRole('ADMIN')")
    public DataResponse honourEditSave(@Valid @RequestBody DataRequest dataRequest) {
        Map form = dataRequest.getMap("form"); //参数获取Map对象
        Integer honourId = Integer.valueOf(CommonMethod.getString(form, "honourId"));
        String number = CommonMethod.getString(form, "number");
        String num = CommonMethod.getString(form, "num");  //Map 获取属性的值
        String name = CommonMethod.getString(form, "name");
        String honourName = CommonMethod.getString(form, "honourName");
        String describe = CommonMethod.getString(form, "describe");
        //先根据 num 在数据库中查询到用户的person_id
        Optional<Person> byNum = personRepository.findByNum(num);
        if(!byNum.isPresent()){  //判断是否获取数据  不是就返回错误提示
            return CommonMethod.getReturnMessageOK("未查询到该用户！");
        }
        if(!byNum.get().getName().equals(name)){   //判断查询出的用户和输入的姓名是否一致
            return CommonMethod.getReturnMessageOK("学号和姓名不是同一个人！");
        }
        Honour h = new Honour();   //封装
        h.setHonourName(honourName);
        h.setNumber(number);
        h.setDescribe(describe);
        h.setPerson(byNum.get());          //byNum.get() 是people数据

        //如果 honourId 存在表示请求为更新数据
        if(honourId != null){
            h.setHonourId(honourId);
            Honour honour = honourRepository.save(h);
            return CommonMethod.getReturnData(honour.getHonourId());
        }
        Honour honour = honourRepository.saveAndFlush(h);
        return CommonMethod.getReturnData(honour.getHonourId());  // 将honourId返回前端
    }
    @PostMapping("/getHonourInfo")
    @PreAuthorize(" hasRole('ADMIN')")
    public DataResponse getHonourInfo(@Valid @RequestBody DataRequest dataRequest) {
        Integer honourId = dataRequest.getInteger("honourId");  //获取要删除的荣誉id
        Optional<Honour> byId = honourRepository.findById(honourId);//通过id查询
        System.out.println(byId.get().getPerson().getNum());
        Map m = new HashMap<>();               //封装
        m.put("honourId",byId.get().getHonourId());
        m.put("number",byId.get().getNumber());
        m.put("honourName",byId.get().getHonourName());
        m.put("describe",byId.get().getDescribe());
        m.put("num",byId.get().getPerson().getNum());
        m.put("name",byId.get().getPerson().getName());
        return  CommonMethod.getReturnData(m);
    }

    public List getHonourMapList(String numName) {
        List dataList = new ArrayList();
        List<Honour> sList = honourRepository.findHonourListByNumName(numName);  //数据库查询操作
        if (sList == null || sList.size() == 0)
            return dataList;
        for (int i = 0; i < sList.size(); i++) {
            dataList.add(honourService.getMapFromHonour(sList.get(i)));
        }
        return dataList;
    }
    @PostMapping("/getHonourListExcl")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public ResponseEntity<StreamingResponseBody> getHonourListExcl(@Valid @RequestBody DataRequest dataRequest) {
        String numName = dataRequest.getString("numName");
        List list = getHonourMapList(numName);
        Integer widths[] = {8, 20, 10, 15, 15};
        int i, j, k;
        String titles[] = {"序号", "学号", "姓名", "奖项", "奖项描述"};
        String outPutSheetName = "honour.xlsx";
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFCellStyle styleTitle = CommonMethod.createCellStyle(wb, 20);
        XSSFSheet sheet = wb.createSheet(outPutSheetName);
        for (j = 0; j < widths.length; j++) {
            sheet.setColumnWidth(j, widths[j] * 256);
        }
        //合并第一行
        XSSFCellStyle style = CommonMethod.createCellStyle(wb, 11);
        XSSFRow row = null;
        XSSFCell cell[] = new XSSFCell[widths.length];
        row = sheet.createRow((int) 0);
        for (j = 0; j < widths.length; j++) {
            cell[j] = row.createCell(j);
            cell[j].setCellStyle(style);
            cell[j].setCellValue(titles[j]);
            cell[j].getCellStyle();
        }
        Map m;
        if (list != null && list.size() > 0) {
            for (i = 0; i < list.size(); i++) {
                row = sheet.createRow(i + 1);
                for (j = 0; j < widths.length; j++) {
                    cell[j] = row.createCell(j);
                    cell[j].setCellStyle(style);
                }
                m = (Map) list.get(i);
                cell[0].setCellValue((i + 1) + "");
                cell[1].setCellValue(CommonMethod.getString(m, "number"));
                cell[2].setCellValue(CommonMethod.getString(m, "num"));
                cell[3].setCellValue(CommonMethod.getString(m, "name"));
                cell[4].setCellValue(CommonMethod.getString(m, "honourName"));
                cell[5].setCellValue(CommonMethod.getString(m, "describe"));
            }
        }
        try {
            StreamingResponseBody stream = outputStream -> {
                wb.write(outputStream);
            };
            return ResponseEntity.ok()
                    .contentType(CommonMethod.exelType)
                    .body(stream);

        } catch (Exception e) {
            return ResponseEntity.internalServerError().build();
        }

    }
}